package cn.wolfcode.luowowo.search.service.impl;

import cn.wolfcode.luowowo.search.dao.ITravelSearchDAO;
import cn.wolfcode.luowowo.search.query.SearchQueryObject;
import cn.wolfcode.luowowo.search.query.StrategySearchQuery;
import cn.wolfcode.luowowo.search.service.ITravelSearchService;
import cn.wolfcode.luowowo.search.template.TravelTemplate;
import com.alibaba.dubbo.config.annotation.Service;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;

import java.util.ArrayList;
import java.util.List;

@Service
public class TravelSearchServiceImpl implements ITravelSearchService {

    @Autowired
    private ITravelSearchDAO travelSearchDAO;


    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;


    @Override
    public void save(TravelTemplate template) {
        travelSearchDAO.save(template);
    }

    @Override
    public void update(TravelTemplate template) {
        travelSearchDAO.deleteById(template.getId());
        this.save(template);
    }

    @Override
    public void delete(Long id) {
        travelSearchDAO.deleteById(id);
    }

    @Override
    public TravelTemplate get(Long id) {
        return travelSearchDAO.findById(id).get();
    }

    @Override
    public List<TravelTemplate> list() {
        Iterable<TravelTemplate> all = travelSearchDAO.findAll();
        List<TravelTemplate> list = new ArrayList<>();
        all.forEach(cc -> list.add(cc));
        return list;
    }

    public Page<TravelTemplate> query(StrategySearchQuery qo) {
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        if (qo.getDestId() != -1) {
            boolQuery.must(QueryBuilders.termQuery("destId", qo.getDestId()));
        }
        return travelSearchDAO.search(boolQuery, qo.getPageableWithSort());
    }

//    @Override
//    public Page<TravelTemplate> query(SearchQuery qo) {
//
//
//        Page<TravelTemplate> page = travelSearchDAO.findAll(qo.getPageable());
//        return page;
//    }


    @Override
    public void createIndex() {
        elasticsearchTemplate.createIndex(TravelTemplate.class);
        elasticsearchTemplate.putMapping(TravelTemplate.class);
    }

    @Override
    public Page<TravelTemplate> searchByDest(SearchQueryObject qo) {
        Page<TravelTemplate> page = Page.empty();
        try {
            page = travelSearchDAO.search(QueryBuilders.termQuery("destId", qo.getDestId()), qo.getPageable());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return page;
    }
}
